package com.xxkj.drugtraceability.ui.drugoutscan

import android.text.Html
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.ActivityDrugscanBinding
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.utils.showCompleteToast
import com.xxkj.drugtraceability.utils.toast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/9/10 18:19
 * description:
 */
class DrugOutScanActivity:BaseVMActivity() {
    private val binding by binding<ActivityDrugscanBinding>(R.layout.activity_drugscan)
    private val viewModel by viewModel<DrugOutScanViewModel>()
    private lateinit var drugScanAdapter: DrugOutScanAdapter
    private var packageModel = "药盒"
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            recyclerView.layoutManager = LinearLayoutManager(this@DrugOutScanActivity)
            drugScanAdapter = DrugOutScanAdapter{
                //删除要强提醒，同意才能删除
                viewModel.dataList.value?.removeAt(it)
                viewModel.dataList.postValue(viewModel.dataList.value)
            }
            recyclerView.adapter = drugScanAdapter
            tvCancel.clickN {
                YellowDialog(this@DrugOutScanActivity,resources.getString(R.string.cancel_all)){
                    //清空所有追溯码
                    finish()
                }
            }
            tvClear.clickN {
                YellowDialog(this@DrugOutScanActivity,resources.getString(R.string.clear_all)){
                    //清空所有追溯码
                    viewModel.clearData()
                }
            }
            tvSave.clickN {
                //调用保存接口
                var alert = false
                var noData = false
                    if (drugScanAdapter.data.isNullOrEmpty()){
                        noData = true
                    }else{
                        if(drugScanAdapter.data.size!=drugInStorageBean?.cnt?.toDouble()
                                ?.toInt()){
                            alert = true
                        }
                    }
                if (noData){
                    //提示没有任何数据
                    YellowDialog(this@DrugOutScanActivity,resources.getString(R.string.no_data),type = 1){

                    }
                }else{
                    if (alert){
                        BlueDialog(this@DrugOutScanActivity,resources.getString(R.string.scan_not_all)){
                            //保存数据
                            drugInStorageBean?.let {
                                it.dataForm = "02"
                                it.drugOutDepotTracInfoList = drugScanAdapter.data
                                val list = mutableListOf<DrugOutStorageBean>()
                                list.add(it)
                                val drugStorageUpRequest = DrugOutUpRequest(list,it.outDepotNo)
                                viewModel.drugInOutStorage(Gson().toJson(drugStorageUpRequest))
                            } }
                    }else{
                        //保存数据
                        drugInStorageBean?.let {
                            it.dataForm = "02"
                            it.drugOutDepotTracInfoList = drugScanAdapter.data
                            val list = mutableListOf<DrugOutStorageBean>()
                            list.add(it)
                            val drugStorageUpRequest = DrugOutUpRequest(list,it.outDepotNo)
                            viewModel.drugInOutStorage(Gson().toJson(drugStorageUpRequest))
                        } }
                }
            }
        }
    }

    private var drugInStorageBean: DrugOutStorageBean? = null
    override fun initData() {
        val data = intent.getStringExtra("data")
        viewModel.hasData = false

         drugInStorageBean = Gson().fromJson(data, DrugOutStorageBean::class.java)
        drugInStorageBean?.let {
            if (it.drugOutDepotTracInfoList != null && it.drugOutDepotTracInfoList!!.isNotEmpty()) {
                viewModel.hasData = true
            }
            viewModel.dataList.postValue(it.drugOutDepotTracInfoList as MutableList<DrugTrace>?)
            binding.apply {
                tvContent.text = it.drugName
                tvDetail.text = "${it.drugSpec?:""}/${it.drugUnit}   ${it.cnt}${it.drugUnit?:""}"
                setCountInfo(tvCountInfo,it)
            }
        }

        if (viewModel.hasData){
            binding.llBottom.visibility = View.GONE
            binding.llTop.visibility = View.GONE
        }
        if (!viewModel.hasData)
            viewModel.isOpenMsfx()
    }

   private fun setCountInfo(tvCountInfo:TextView,drugInStorageBean:DrugOutStorageBean){
       val buffer1 = StringBuffer()
       buffer1.append("<font color='#33333F'>")
       buffer1.append("已扫/未扫：")
       buffer1.append("</font>")
       buffer1.append("<font color='#42C697' size='50px'>")
       if (viewModel.dataList.value.isNullOrEmpty())
           buffer1.append(0)
       else buffer1.append(viewModel.dataList.value!!.size)
       buffer1.append("</font>")
       buffer1.append("<font color='#494953' size='50px'>")
       buffer1.append("/")
       buffer1.append("</font>")
       buffer1.append("<font color='#F7745C' size='50px'>")
       if (viewModel.dataList.value.isNullOrEmpty())
           buffer1.append(drugInStorageBean.cnt)
       else{
           if (drugInStorageBean.cnt<=viewModel.dataList.value!!.size){
               buffer1.append(0)
           }else{
               buffer1.append(drugInStorageBean.cnt-viewModel.dataList.value!!.size)
           }
       }
       buffer1.append("</font>")
       tvCountInfo.text = Html.fromHtml(buffer1.toString())
    }

    override fun startObserve() {
        viewModel.dataList.observe(this, Observer {
            drugInStorageBean?.let {drugInStorageBean ->
                setCountInfo(binding.tvCountInfo,drugInStorageBean)
            }
            drugScanAdapter.setState(viewModel.hasData)
            drugScanAdapter.setList(it)
        })
        viewModel.uiState.observe(this, Observer {
            if (it.isSuccess==true){
                showCompleteToast(this)
                binding.recyclerView.postDelayed({
                    setResult(3333)
                    finish()
                },1500L)
            }
            if (it.isLoading){
                showMyDialog(resources.getString(R.string.saveing_data))
            }else{
                dismissMyDialog()
            }
            if (!it.isError.isNullOrEmpty()){
                BlueDialog(this,it.isError!!,type = 1){}
            }
        })
        viewModel.isShowMsfxRadio.observe(this, {
            binding.radioGroup.visibility = View.VISIBLE
            binding.radioGroup.setOnCheckedChangeListener { group, checkId ->
                if (binding.radioChest.id == binding.radioGroup.checkedRadioButtonId)
                    packageModel = binding.radioChest.tag.toString()
            }
        })
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@DrugOutScanActivity)&&!viewModel.hasData){
                        val barcodeMessage = this.any as BarcodeMessage
                        if(barcodeMessage.type== BarcodeType.SUYUAN){
                            viewModel.dataList.value?.forEach {
                                if (it.drugTracCodg==barcodeMessage.barcode){
                                    toast(R.string.scan_code_has)
                                    return@apply
                                }
                            }
                            if (packageModel == "药箱") {
                                viewModel.queryTracCodeByBoxCode(barcodeMessage.barcode)
                            } else {
                                viewModel.data.add(DrugTrace(drugTracCodg = barcodeMessage.barcode))
                                viewModel.dataList.postValue(viewModel.data)
                            }
                        }else{
                            viewModel.queryTracCodeByBoxCode(barcodeMessage.barcode)
//                            YellowDialog(this@DrugOutScanActivity,resources.getString(R.string.scan_suyuan),type = 1){}
                        }

                    }
                }
            }
        }
    }
    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}